<template>
  <main-card title="算法测试" :loading="loading" :show-screen-space="false" :online-lab="true">
    <template #tool-btn>
      <a-button type="primary" @click="openAddTaskModal">创建任务</a-button>
    </template>

    <div class="mb-44 fbc">
      <a-select v-model:value="pageForm.status" class="w-140" :options="typeOptions" @change="getDataList({ offset: 1 })" />
      <div class="flex-1"></div>
      <a-input
        v-model:value="pageForm.name"
        v-trim
        class="h-36"
        allow-clear
        placeholder="请输入名称"
        style="width: 328px"
        @keyup.enter="getDataList({ offset: 1 })"
      >
        <template #prefix> <i class="iconfont icon-search-line"></i> </template>
      </a-input>
    </div>
    <div class="page-table">
      <a-table
        :columns="tableColumns"
        :data-source="dataList"
        :pagination="false"
        :style="{ width: '100%' }"
        :custom-row="r => ({ onClick: () => handleToDetail(r.id) })"
        @change="tableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'status'">
            <div :class="['table__status', getTaskStatusItem(record.status).isError && 'error']">
              {{ getTaskStatusItem(record.status).title }}
            </div>
          </template>
          <template v-else-if="column.dataIndex === 'operate'">
            <a-dropdown placement="bottom" @click.stop>
              <a-button type="text" class="icon-only-btn" :data-share="record?.createType === 1" @click.stop>
                <i class="iconfont icon-more-line"></i>
              </a-button>
              <template #overlay>
                <a-menu>
                  <a-menu-item class="menu-icon-item" @click="goOperationRecord(record.id, record.name)"> 记录 </a-menu-item>
                  <a-menu-item v-if="isCanDownload(record.status)" class="menu-icon-item" @click="downloadTask(record.id)">
                    下载
                  </a-menu-item>
                  <a-menu-item
                    v-if="checkPermissions(record?.createType, record?.readOnly)"
                    class="menu-icon-item"
                    @click="openDeleteTaskModal(record)"
                  >
                    删除
                  </a-menu-item>
                  <a-menu-item
                    v-if="checkPermissions(record?.createType, record?.readOnly)"
                    class="menu-icon-item"
                    @click="handleOpenShareModal(record)"
                  >
                    分享
                  </a-menu-item>
                  <template v-if="checkPermissions(record?.createType, record?.readOnly)">
                    <a-menu-item v-if="isCanStatStop(record.status)" class="menu-icon-item" @click="handleStatStop(record)">
                      {{ getStatStopName(record.status) }}
                    </a-menu-item>
                  </template>
                </a-menu>
              </template>
            </a-dropdown>
          </template>
          <template v-else-if="column.dataIndex === 'beforeRunTime'">
            {{ spliceTwoTimes(record.startTime, record.endTime) }}
          </template>
        </template>
      </a-table>
    </div>

    <g-pagination v-model:offset="pageForm.offset" v-model:limit="pageForm.limit" :total="pageForm.total" @change="getDataList" />
  </main-card>

  <a-modal
    v-model:open="addTaskVisible"
    title="创建任务"
    :mask-closable="false"
    width="416px"
    centered
    :after-close="afterClose"
    :confirm-loading="createLoadingBtn"
    @ok="addTask"
  >
    <a-form ref="addFormRef" layout="vertical" :rules="rules" :model="addForm">
      <a-form-item label="任务名称" name="name">
        <a-input v-model:value="addForm.name" v-trim placeholder="请输入任务名称" :maxlength="200" />
      </a-form-item>
      <a-form-item label="测试指标" name="normIds">
        <a-select
          v-model:value="addForm.normIds"
          :show-search="false"
          :options="normList"
          mode="multiple"
          max-tag-count="responsive"
          placeholder="请选择测试指标"
          style="width: 100%"
        />
      </a-form-item>
    </a-form>
  </a-modal>

  <delete-confirm-dialog
    v-model:show="isDeleteDialogShow"
    :loading="confirmLoading"
    :confirm-name="currentDeleteTaskItem?.name"
    @ok="onOkDeleteTask"
  />

  <share-modal
    ref="shareModalRef"
    :submit-api="algoTestApi.share"
    :remove-user-api="algoTestApi.removeShareUser"
    :get-list-api="algoTestApi.getShareList"
  />
</template>

<script setup lang="ts">
  import { FormInstance, message, Modal, TableProps } from 'ant-design-vue'
  import { ref } from 'vue'
  import { useRequest } from 'vue-request'
  import { useRouter } from 'vue-router'

  import DeleteConfirmDialog from '@/components/DeleteConfirmDialog/index.vue'
  import GPagination from '@/components/GPagination/index.vue'
  import MainCard from '@/components/MainCard/index.vue'
  import ShareModal from '@/components/ShareModal/index.vue'
  import useList from '@/hooks/use-list'
  import { algoTestApi } from '@/services/api'
  import { spliceTwoTimes, validateBitLen, validateDirName, waitLoading } from '@/utils'
  import { filterTableColumns } from '@/utils/ant-component'
  import { checkPermissions } from '@/utils/share'

  import { getTaskStatusItem, normList, TaskStatus, taskStatusList } from '../options'

  type TaskItem = {
    endTime: null | string
    startTime: null | string
    createTime: string
    id: string
    status: TaskStatus
    name: string
  }

  interface PageForm {
    name: string
    status: string
    order: 'desc' | 'asc'
    columns: 'createTime' | ''
  }

  const router = useRouter()

  type TableDataType = {
    key: string
    name: string
    age: number
    address: string
  }

  // 表格
  const tableColumns = ref(
    filterTableColumns([
      {
        title: '名称',
        dataIndex: 'name',
        width: 240
      },
      {
        title: '状态',
        dataIndex: 'status',
        minWidth: 200
      },
      {
        title: '运行起止时间',
        dataIndex: 'beforeRunTime',
        minWidth: 360
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        width: 190,
        isSort: true
      },

      {
        title: '操作',
        width: 80,
        dataIndex: 'operate'
      }
    ])
  )

  // 类型
  const typeOptions = [
    {
      label: '全部状态',
      value: ''
    },
    ...taskStatusList.map(it => ({
      label: it.name,
      value: it.status
    }))
  ]

  const { pageForm, dataList, loading, getDataList } = useList<PageForm, TaskItem>(algoTestApi.list, {
    name: '',
    status: '',
    columns: '',
    order: 'desc'
  })

  // 表格变化
  const tableChange: TableProps<TableDataType>['onChange'] = (pagination, filters, sorter: any) => {
    pageForm.value.order = sorter.order === 'ascend' ? 'asc' : 'desc'
    pageForm.value.columns = sorter.field
    if (!sorter.order) {
      pageForm.value.columns = 'createTime'
      pageForm.value.order = 'desc'
    }
    getDataList({ offset: 1 })
  }
  getDataList()

  // 去运行记录
  const goOperationRecord = (id: string, name: string) => {
    router.push(`/algo-test/record-list/${id}?name=${name}`)
  }

  const downloadTask = (id: string) => {
    waitLoading<ResponseData<string>>(getDownloadUrl(id), {
      loadingText: '数据准备中,请耐心等待...',
      errorText: '文件下载失败'
    })
  }

  const getDownloadUrl = async (taskId: string) => {
    const { data } = await algoTestApi.getDownloadUrl(taskId)()
    window.open(data)
    return data
  }

  // 跳转到详情
  const handleToDetail = (id: string) => {
    router.push(`/algo-test/task-edit/${id}`)
  }

  const isCanDownload = (status: number) => [3, 4, 5].includes(status)
  const isCanStatStop = (status: number) => [1, 2, 7, 8].includes(status)

  const getStatStopName = (status: number) => {
    return [7].includes(status) ? '启动' : '停止'
  }

  /* 新增测试任务 ----------------------------------------------------------------- */
  const addTaskVisible = ref(false)

  const addFormRef = ref<FormInstance>()
  const addForm = ref({
    name: '',
    normIds: []
  })

  const rules = {
    name: [{ required: true, message: '请输入任务名称' }, { validator: validateBitLen(200) }, { validator: validateDirName() }],
    normIds: [
      {
        required: true,
        message: '请选择测试指标'
      }
    ]
  }

  const openAddTaskModal = () => {
    addTaskVisible.value = true
  }

  const afterClose = () => {
    addFormRef.value?.resetFields()
    createLoadingBtn.value = false
  }

  // userRequest
  const { data: addTaskRes, runAsync: runAddTask, loading: createLoadingBtn } = useRequest<ResponseData<string>>(algoTestApi.add)
  const addTask = async () => {
    await addFormRef.value?.validateFields()
    await runAddTask(addForm.value, { isAddUid: true })
    handleToDetail(addTaskRes.value?.data || '')
    message.success('添加成功')
    addTaskVisible.value = false
  }

  /* 删除测试任务 ----------------------------------------------------------------- */
  const currentDeleteTaskItem = ref<any>()
  const isDeleteDialogShow = ref(false)

  const openDeleteTaskModal = (item: any) => {
    currentDeleteTaskItem.value = item
    isDeleteDialogShow.value = true
  }

  /*----------------------------------------- 分享 --------------------------------*/
  const shareModalRef = ref<InstanceType<typeof ShareModal>>()
  const handleOpenShareModal = (item: any) => {
    shareModalRef.value?.open({
      id: item.id
    })
  }
  const handleStatStop = async (item: any) => {
    // 启动任务
    if (item.status === 7) {
      await algoTestApi.startTask({
        taskId: item.id
      })
      message.success('操作成功')
      getDataList()
      return
    }
    // 停止任务
    Modal.confirm({
      title: '此任务将暂停测试，请确认是否操作',
      async onOk() {
        await algoTestApi.stopTask({
          taskId: item.id
        })
        message.success('操作成功')
        getDataList()
      }
    })
  }

  // 确认删除
  const { loading: confirmLoading, runAsync: runDelAlgoTest } = useRequest(algoTestApi.del)
  const onOkDeleteTask = async () => {
    await runDelAlgoTest({}, { urlParams: { id: currentDeleteTaskItem.value?.id || '' } })
    message.success('删除成功')
    isDeleteDialogShow.value = false
    getDataList()
  }
</script>

<style lang="less" scoped>
  .page-top {
    padding: 12px 0;
    // width: 100%;
    box-sizing: border-box;

    .pagetop-active {
      color: rgba(29, 32, 132, 1);
      background-color: transparent;
      border: none !important;
      box-shadow: none;
    }

    & > .ant-col {
      display: flex;
      align-items: center;
    }

    .ant-col + .ant-col {
      margin-left: 16px;
    }
  }

  .py-4 {
    padding: 4px 0;
  }
</style>
..
